import fs from "fs";
import path from "path";

export class FileUtil {
    /**
     * 确保目录存在，不存在就递归创建
     * @param {string} dirPath 目录路径
     */
    static ensureDir(dirPath) {
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    }

    /**
     * 在指定根目录下查找同名子目录
     * @param {string} rootDir 搜索起点
     * @param {string} dirName 目标目录名
     * @param {{maxDepth?: number, limit?: number, skipDirNames?: string[]}} options 配置项
     * @returns {string[]} 命中的目录绝对路径（按层级浅→深排序，最多 limit 个）
     */
    static findDirsByName(rootDir, dirName, options = {}) {
        const results = [];
        const normalizedName = (dirName || '').trim();
        if (!normalizedName) {
            return results;
        }
        const normalizedRoot = path.resolve(rootDir || '');
        if (!fs.existsSync(normalizedRoot)) {
            return results;
        }
        let stat;
        try {
            stat = fs.lstatSync(normalizedRoot);
        } catch (e) {
            return results;
        }
        if (!stat.isDirectory()) {
            return results;
        }
        const maxDepth = Number.isInteger(options.maxDepth) ? Math.max(0, options.maxDepth) : 4;
        const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 10;
        const skipDirNames = new Set(options.skipDirNames || ['.git', 'node_modules', '.idea', '.vscode', '.husky']);

        if (path.basename(normalizedRoot) === normalizedName) {
            results.push(normalizedRoot);
            if (results.length >= limit) {
                return results;
            }
        }

        const stack = [{dir: normalizedRoot, depth: 0}];
        while (stack.length > 0 && results.length < limit) {
            const {dir, depth} = stack.pop();
            let entries;
            try {
                entries = fs.readdirSync(dir, {withFileTypes: true});
            } catch (e) {
                continue;
            }
            for (const entry of entries) {
                if (!entry.isDirectory()) {
                    continue;
                }
                if (typeof entry.isSymbolicLink === 'function' && entry.isSymbolicLink()) {
                    continue;
                }
                if (skipDirNames.has(entry.name)) {
                    continue;
                }
                const fullPath = path.join(dir, entry.name);
                if (entry.name === normalizedName) {
                    results.push(fullPath);
                    if (results.length >= limit) {
                        break;
                    }
                }
                if (depth < maxDepth) {
                    stack.push({dir: fullPath, depth: depth + 1});
                }
            }
        }
        // 按层级浅→深排序，避免返回过深的目录
        return results.sort((a, b) => a.split(path.sep).length - b.split(path.sep).length);
    }
}
